trigger TemplateInUse on Template__c (before delete, before update) {
    if(Trigger.isDelete){
       for(Template__c t: Trigger.old){
          for(Batch__c b : [Select Status__c from Batch__c b where b.Template__c = :t.Id])
          {
              if(b.Status__c == 'Distributed')
                  t.addError('This template cannot be deleted as it has been used to generate Plan Documents.');          
          }
       }
   }

    if(Trigger.isUpdate)
    {
    	Map<ID,User> uMap = new Map<ID, User>{};
    	ID[] uList = new ID[]{};
    	for(Template__c t: Trigger.new)
    	{
    		uList.add(t.createdById);
    	}
    	
    	User[] users = [select id, firstname, email from User where id in :uList];
    	for(User u: users)
    	{
    		uMap.put(u.id, u);
    	}
        Messaging.SingleEmailMessage[] mailList = new Messaging.SingleEmailMessage[]{};   
        Template__c[] errorTemplateList = new Template__c[]{};                                           
    	for(Template__c t: Trigger.new)
       	{
        	Schema.Describesobjectresult tSobject = Template__c.getSObjectType().getDescribe();
        	if(!tSobject.isAccessible() || !tSobject.isCreateable() || !tSobject.isUpdateable() || !tSobject.isDeletable())
        	{
		      	Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
	            String actingUserName = UserInfo.getName();
	            User u = uMap.get(t.createdById);
	            String[] toAddresses = new String[] {u.Email}; 
	          	mail.setToAddresses(toAddresses);
	            mail.setSubject(actingUserName+' tried to update the Template '+t.Name);
	            mail.setBccSender(false);
	            mail.setUseSignature(false);
	            mail.setPlainTextBody(actingUserName+' tried to update the Template '+t.Name);
	            mail.setHtmlBody('Dear <b>'+u.FirstName+'</b>,<br/><br/>'+actingUserName+' tried to perform CRUD operation on the Template '+t.Name+'.<br/><br/>Thanks');
	            mailList.add(mail);
    			errorTemplateList.add(t);
            	
        	}
       	}

       	Messaging.sendEmail(mailList);
       	for(Template__c t: errorTemplateList)
       	{
			t.addError('User has insufficient privileges on Template object');			       		
       	}
   }
}